import React, { Component } from "react"
import InfoTable from "../common/sourceTable"
import { Card, Button, Popconfirm, message } from "antd"
import { FormInstance } from 'antd/lib/form'
import { EditFilled, DeleteFilled } from '@ant-design/icons'
import { getMoveInfo, addMove, editMove, delMove } from "@net/move/index"
import DialogForm from '../common/dialogForm'
import Modal from '@comp/Modal'
import HeaderSearch from '../common/headerSearch'
import DialogTable from '../common/dialogTable'
import "../../index.scss"
import Power from "@comm/power"
import moment from 'moment'
import { getGoodInsInfo } from "@net/good/inspection"
import city from '@assets/js/citydata'
import { getDisInfo } from "@net/company/distributor"
import {getConInvalid} from '@comm/utils'

interface IPorps { }
interface IStates {
    data: any[]
    loading: boolean,
    popVisible: string,
    visible: boolean,
    title: string,
    delId: number,
    editId: number,
    isEdit: boolean,
    page: number,
    pageSize: number,
    total: number,
    diaTabDataFn: any[],
    diaVisbleFn: boolean,
    diaTabDataSu: any[],
    diaVisbleSu: boolean,
    diaTable: string,
    search: any,
    insId:number,
}

export default class GoodMove extends Component<IPorps, IStates> {
    // 表格设置
    private column = [
        {
            key: "traPro",
            dataIndex: "traPro",
            title: "货物名称",
            align: "center",
            fixed: 'left',
            ellipsis:true
        },
        {
            key: "do",
            dataIndex: "do",
            title: "操作",
            align: "center",
            fixed: 'left',
            render: (text: any, record: any) => {
                const item = record
                return (
                    <div className="do">
                        <Power authKey="move:info:update">
                            <Button size="small" type="primary" icon={<EditFilled />} onClick={() => { this.openEditDia(item) }} />
                        </Power>
                        <Power authKey="move:info:remove">
                            <Popconfirm title="您确定要删除吗？" okText="是" cancelText="否"
                                onConfirm={this.delete} visible={item.key === this.state.popVisible}
                                onCancel={() => { this.setState({ popVisible: "-1" }) }}>
                                <Button size="small" danger icon={<DeleteFilled />} onClick={() => { this.openPopDia(item) }} />
                            </Popconfirm>
                        </Power>
                    </div>
                )
            }
        },
        {
            key: "traNum",
            dataIndex: "traNum",
            title: "货物数量",
            align: "center"
        },
        {
            key: "traSpecs",
            dataIndex: "traSpecs",
            title: "货物规格",
            align: "center"
        },
        {
            key: "traPerson",
            dataIndex: "traPerson",
            title: "运输人员",
            align: "center",
        },
        {
            key: "vehicle",
            dataIndex: "vehicle",
            title: "运输车辆",
            align: "center"
        },
        {
            key: "traMode",
            dataIndex: "traMode",
            title: "运输方式",
            align: "center",
            render:(text:string) => {
                switch(text){
                    case "0" : return "铁路运输";
                    case "1" : return "公路运输";
                    case "2" : return "航空运输";
                    case "3" : return "水路运输";
                    default : return ""
                }
            }
        },
        {
            key: "traSendTime",
            dataIndex: "traSendTime",
            title: "发货时间",
            align: "center"
        },
        {
            key: "traRecTime",
            dataIndex: "traRecTime",
            title: "收货时间",
            align: "center"
        },
        {
            key: "deliveryPlace",
            dataIndex: "deliveryPlace",
            title: "发货地点",
            align: "center",
            ellipsis:true
        },
        {
            key: "recievePlace",
            dataIndex: "recievePlace",
            title: "收货地点",
            align: "center",
            ellipsis:true
        },
        {
            key: "distributor",
            dataIndex: "distributor",
            title: "经销商",
            align: "center",
            ellipsis:true
        },
        {
            key: "distributorPer",
            dataIndex: "distributorPer",
            title: "经销商负责人",
            align: "center"
        },
        {
            key: "distributorTel",
            dataIndex: "distributorTel",
            title: "经销联系方式",
            align: "center"
        },
    ]
    private columnDiaFn = [
        {
            title: "名称",
            dataIndex: "insName",
            align: "center",
            fixed: "left"
        },
        {
            title: "质量审核",
            dataIndex: "insVerify",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" danger>未通过</Button>
                } else if (text === "1") {
                    return text = <Button type="link">审核通过</Button>
                } else {
                    return text = <Button type="link" className="agree">待审核</Button>
                }
            },
            fixed: "left"
        },
        {
            title: "有无气味",
            dataIndex: "insSmell",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" >无</Button>
                } else if (text === "1") {
                    return text = <Button type="link" danger>有</Button>
                } else {
                    return text = <Button type="link" className="agree">其它</Button>
                }
            }
        },
        {
            title: "有无杂质",
            dataIndex: "insImpurity",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" >无</Button>
                } else if (text === "1") {
                    return text = <Button type="link" danger>有</Button>
                } else {
                    return text = <Button type="link" className="agree">其它</Button>
                }
            }
        },
        {
            title: "成分含量",
            dataIndex: "insComposition",
            align: "center"
        },
        {
            title: "重金属",
            dataIndex: "insHeavyMetal",
            align: "center",
            render: (text: any) => {
                if (text === "0") {
                    return text = <Button type="link" danger>无</Button>
                } else if (text === "1") {
                    return text = <Button type="link">有</Button>
                } else {
                    return text = <Button type="link" className="agree">其它</Button>
                }
            }
        },
        {
            title: "生物指标(菌落)",
            dataIndex: "insBiomarker",
            align: "center"
        },
        {
            title: "有毒物质",
            dataIndex: "insToxicSub",
            align: "center"
        },
        {
            title: "检测人员",
            dataIndex: "insPerson",
            align: "center"
        },
        {
            title: "检测机构",
            dataIndex: "insCompany",
            align: "center"
        },
        {
            title: "检测时间",
            dataIndex: "insCreatetime",
            align: "center"
        },
        {
            title: "备注(原因)",
            dataIndex: "insRemark",
            align: "center"
        }
    ]
    private columnDiaSu = [
        {
            key: "disName",
            dataIndex: "disName",
            title: "名称",
            align: "center"
        },
        {
            key: "disLeader",
            dataIndex: "disLeader",
            title: "负责人",
            align: "center"
        },
        {
            key: "disPhone",
            dataIndex: "disPhone",
            title: "联系电话",
            align: "center"
        },
        {
            key: "disPlace",
            dataIndex: "disPlace",
            title: "地址",
            align: "center",
        },
        {
            key: "disConStart",
            dataIndex: "disConStart",
            title: "合同生效时间",
            align: "center"
        },
        {
            key: "disConEnd",
            dataIndex: "disConEnd",
            title: "合同失效时间",
            align: "center"
        },
    ]
    private dialogFormCol = () => {
        return [
            {
                type: 'input',
                label: "货物名称",
                name: "traPro",
                rules: [
                    { required: true, message: "请输入名称" }
                ],
                component: {
                    placeholder: "请输入名称",
                    disabled: this.state.isEdit === false ? false : true
                },
                style: { borderRadius: "5px" },
                id: "moTraName",
                onFocus: () => { this.openDiaTable("fn") },
            },
            {
                type: 'input',
                label: "货物数量",
                name: "traNum",
                rules: [
                    { required: true, message: "请输入数量" }
                ],
                component: {
                    placeholder: "请输入数量",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "货物规格",
                name: "traSpecs",
                rules: [
                    { required: true, message: "请输入规格" }
                ],
                component: {
                    placeholder: "请输入规格",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "运输人员",
                name: "traPerson",
                rules: [
                    { required: true, message: "请输入运输人员" }
                ],
                component: {
                    placeholder: "请输入运输人员",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "运输车辆",
                name: "vehicle",
                rules: [
                    { required: true, message: "请输入运输车辆" }
                ],
                component: {
                    placeholder: "请输入运输车辆",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'select',
                label: "运输方式",
                name: "traMode",
                option:[
                    {value:"铁路运输",key:"0"},
                    {value:"公路运输",key:"1"},
                    {value:"航空运输",key:"2"},
                    {value:"水路运输",key:"3"},
                ],
                rules: [
                    { required: true, message: "请输入运输方式" }
                ],
                component: {
                    placeholder: "请输入运输方式",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'datePicker',
                label: "发货时间",
                name: "traSendTime",
                rules: [
                    { required: true, message: "请选择发货时间" }
                ],
                component: {
                    placeholder: "请选择发货时间",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'datePicker',
                label: "收货时间",
                name: "traRecTime",
                rules: [
                    { required: true, message: "请选择收货时间" }
                ],
                component: {
                    placeholder: "请选择收货时间",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'cascader',
                label: "发货地",
                name: "deliveryPlace",
                rules: [
                    { required: true, message: "请输入发货地" }
                ],
                option: city,
                component: {
                    placeholder: "请输入发货地",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'cascader',
                label: "收货地",
                name: "recievePlace",
                rules: [
                    { required: true, message: "请输入收货地" }
                ],
                option: city,
                component: {
                    placeholder: "请输入收货地",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "经销商",
                name: "distributor",
                rules: [
                    { required: true, message: "请输入经销商" }
                ],
                component: {
                    placeholder: "请输入经销商",
                },
                style: { borderRadius: "5px" },
                id: "moDisName",
                onFocus: () => { this.openDiaTable("su") },
            },
            {
                type: 'input',
                label: "经销商负责人",
                name: "distributorPer",
                rules: [
                    { required: true, message: "请输入经销商负责人" }
                ],
                component: {
                    placeholder: "请输入经销商负责人",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'input',
                label: "经销商联系方式",
                name: "distributorTel",
                rules: [
                    { required: true, message: "请输入经销商联系方式" }
                ],
                component: {
                    placeholder: "请输入经销商联系方式",
                },
                style: { borderRadius: "5px" }
            },

        ]
    }
    private searchCol = [
        {
            type: 'input',
            name: "fname",
            label: "食品名称",
            component: {
                placeholder: "请输入食品名称",
            },
            style: { borderRadius: "5px" }
        },
        {
            type: 'select',
            name: "fmode",
            label: "运输方式",
            option:[
                {value:"铁路运输",key:"0"},
                {value:"公路运输",key:"1"},
                {value:"航空运输",key:"2"},
                {value:"水路运输",key:"3"},
            ],
            component: {
                placeholder: "请选择运输方式",
            },
            style: { borderRadius: "5px",width:"200px" }
        }
    ]
    private dialogFormRef = React.createRef<FormInstance>() as any
    constructor(props: IPorps) {
        super(props)
        this.state = {
            data: [],
            loading: true,
            popVisible: "-1",
            visible: false,
            title: "",
            delId: 0,
            editId: 0,
            isEdit: false,
            total: 0,
            page: 1,
            pageSize: 5,
            diaTabDataFn: [],
            diaVisbleFn: false,
            diaTabDataSu: [],
            diaVisbleSu: false,
            diaTable: "",
            search: null,
            insId:0,
        }
    }
    public componentDidMount() {
        this.fetchData(1, 5)
    }
    // 获取数据
    public fetchData = async (page: number, pageSize: number) => {
        const res = await getMoveInfo({ page, pageSize }, this.state.search)
        res.data.data.map((item: any) => {
            return item.key = item.Id
        })
        this.setState({ loading: false, data: res.data.data, total: res.data.total })
    }
    // 页码切换监听事件
    public pageChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            this.setState({ page, pageSize }, () => {
                this.fetchData(page, pageSize)
            })
        }
    }
    // 弹框表格页码切换监听事件
    public pageDiaChange = (page?: number, pageSize?: number) => {
        if (this.state.diaTable === "fn") {
            if (pageSize && page) {
                getGoodInsInfo({ page, pageSize }, null).then((res: any) => {
                    res.data.data.forEach((item: any) => {
                        item.key = item.code
                    })
                    this.setState({ diaTabDataFn: res.data.data, total: res.data.total })
                })
            }
        }
        if (this.state.diaTable === 'su') {
            if (pageSize && page) {
                getDisInfo({ page, pageSize }).then((res: any) => {
                    res.data.data.forEach((item: any) => {
                        item.key = item.code
                    })
                    this.setState({ diaTabDataSu: res.data.data, total: res.data.total })
                })
            }
        }
    }
    public search = (item: any) => {
        if (item.fname === undefined && item.fmode === undefined) {
            this.setState({ search: null }, () => {
                this.fetchData(this.state.page, this.state.pageSize)
            })
            return
        }
        this.setState({ search: item }, async() => {
            const res = await getMoveInfo({ page: 1, pageSize: 5 }, this.state.search)
            const { status, msg, data,total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ data: data,total })
            }
        })
    }
    // 打开对话框
    public openAddDialog = () => {
        this.setState({ visible: true, title: "食品运输添加", isEdit: false })
    }
    public openEditDia = (item: any) => {
        this.setState({ visible: true, title: "食品运输编辑", editId: item.Id, isEdit: true }, () => {
            item.traRecTime = moment(item.traRecTime, 'YYYY/MM/DD')
            item.traSendTime = moment(item.traSendTime, 'YYYY/MM/DD')
            item.deliveryPlace = item.deliveryPlace.split("-")
            item.recievePlace = item.recievePlace.split("-")
            this.dialogFormRef.current.setFieldsValue(item)
        })
    }
    public openPopDia = (item: any) => {
        this.setState({ popVisible: item.key, delId: item.Id })
    }
    // 打开选择货物弹框
    public openDiaTable = (item: string) => {
        this.setState({ diaTable: item })
        if (item === "fn") {
            this.setState({ diaVisbleFn: true }, () => {
                this.pageDiaChange(1, 5)
            })
        }
        if (item === "su") {
            this.setState({ diaVisbleSu: true }, () => {
                this.pageDiaChange(1, 5)
            })
        }
    }
    // table弹框搜索
    public diaSearch = async (name?: string) => {
        let res: any
        if (this.state.diaTable === "fn") {
            name === "" ?
                res = await getGoodInsInfo({ page: 1, pageSize: 5 }, null)
                :
                res = await getGoodInsInfo({ page: 1, pageSize: 1 }, {fname:name})
            const { status, msg, data,total} = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ diaTabDataFn: data,total })
            }
        }
        if (this.state.diaTable === "su") {
            name === "" ?
                res = await getDisInfo({ page: 1, pageSize: 5 })
                :
                res = await getDisInfo({ page: 1, pageSize: 1 }, name)
            const { status, msg, data,total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ diaTabDataSu: data,total })
            }
        }

    }
    // 点击对话框确认事件
    public onAddOk = () => {
        this.dialogFormRef.current.validateFields(this.add())
    }
    public onEditOk = () => {
        this.dialogFormRef.current.validateFields(this.edit())
    }
    public add = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.insId = this.state.insId
        values.traRecTime = moment(values.traRecTime).format("YYYY/MM/DD")
        values.traSendTime = moment(values.traSendTime).format("YYYY/MM/DD")
        addMove(values).then((res: any) => {
            const { msg, status } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else if (status === 200) {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.cancel()
                this.fetchData(this.state.page, this.state.pageSize)
            }
        })
    }
    public edit = async () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.Id = this.state.editId
        values.insId = this.state.insId
        values.traRecTime = moment(values.traRecTime).format("YYYY/MM/DD")
        values.traSendTime = moment(values.traSendTime).format("YYYY/MM/DD")
        const res = await editMove(values)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.cancel()
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public delete = async () => {
        const res = await delMove(this.state.delId)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.setState({ popVisible: "-1" })
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public cancel = () => {
        this.setState({ visible: false, isEdit: false })
        this.fetchData(this.state.page, this.state.pageSize)
        this.dialogFormRef.current.resetFields()
    }
    public selectRowFn = (item: any) => {
        if(item.insVerify === '0'){
            message.warn({content:'该食品原料审未通过',style:{marginTop:"20%"}})
            return
        }else if(item.insVerify === '2') {
            message.warn({content:'该食品原料未审核',style:{marginTop:"20%"}})
            return
        }
        this.dialogFormRef.current.setFieldsValue({ traPro: item.insName })
        this.setState({ diaVisbleFn: false,insId:item.Id })
    }
    public selectRowSu = (item: any) => {
        let invalid = getConInvalid(item.disConStart,item.disConEnd)
        if(!invalid){
            message.warn({ content: '合同已失效', style: { marginTop: "20%" } })
            return
        }
        this.dialogFormRef.current.setFieldsValue(
            { distributor: item.disName, distributorPer: item.disLeader, distributorTel: item.disPhone })
        this.setState({ diaVisbleSu: false })
    }
    public getDiaContent = (item: string) => {
        if (item === "fn") {
            return (
                <DialogTable
                    columns={this.columnDiaFn}
                    dataSource={this.state.diaTabDataFn}
                    pageChange={this.pageDiaChange}
                    total={this.state.total}
                    scroll={{ x: 1400 }}
                    selectRow={this.selectRowFn}
                    search={this.diaSearch}>
                </DialogTable>
            )
        }
        if (item === "su") {
            return (
                <DialogTable
                    columns={this.columnDiaSu}
                    dataSource={this.state.diaTabDataSu}
                    pageChange={this.pageDiaChange}
                    total={this.state.total}
                    scroll={{ x: 1400 }}
                    selectRow={this.selectRowSu}
                    search={this.diaSearch}
                    label="经销商名称"
                    placeholder="请输入经销商名称">
                </DialogTable>
            )
        }
    }
    public renderDiaTab = (item: string) => {
        if (item === "fn") {
            return (<Modal
                title="选择食品"
                visible={this.state.diaVisbleFn}
                content={this.getDiaContent(this.state.diaTable)}
                width="1200px"
                onCancel={() => { this.setState({ diaVisbleFn: false }) }}
            />
            )
        }
        if (item === "su") {
            return (<Modal
                title="选择经销商"
                visible={this.state.diaVisbleSu}
                content={this.getDiaContent(this.state.diaTable)}
                width="1200px"
                onCancel={() => { this.setState({ diaVisbleSu: false }) }}
            />
            )
        }
    }
    public getContent = () => {
        return (
            <DialogForm ref={this.dialogFormRef} column={this.dialogFormCol()} go={() => { }}></DialogForm>
        )
    }
    // 渲染添加、编辑弹框
    public renderModal = (item?: string) => {
        return (<Modal
            title={this.state.title}
            visible={this.state.visible}
            content={this.getContent()}
            width="1000px"
            onOk={item === "" ? this.onAddOk : this.onEditOk}
            onCancel={this.cancel}></Modal>)
    }
    public renderButton() {
        return (
            <div>
                <Power authKey="move:info:save">
                    <Button type="primary" onClick={() => { this.openAddDialog() }}>新增运输</Button>
                </Power>
            </div>
        )
    }
    public render() {
        return (
            <div className="source">
                <Card className="card">
                    <HeaderSearch
                        authKey="move:info:list"
                        column={this.searchCol}
                        search={this.search}></HeaderSearch>
                    {this.renderButton()}
                    <InfoTable
                        columns={this.column}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        pageChange={this.pageChange}
                        total={this.state.total}
                        scroll={{ x: 1700 }}>
                    </InfoTable>
                </Card>
                {this.state.title === "食品运输添加" ? this.renderModal("") : this.renderModal()}
                {this.renderDiaTab("fn")}
                {this.renderDiaTab("su")}
            </div>
        )
    }
}